package com.bysc.commentservice.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.bysc.commonutils.constant.RedisConstant.CACHE_NULL_TTL;

/**
 * 缓存工具类
 */
@Component
@Slf4j
public class RedisUtils {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加缓存的方法
     */
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        try {
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
        } catch (Exception e) {
            log.error("缓存写入失败!",e);
        }
    }

    /**
     * 解决缓存穿透的封装方法
     */
    public <R, ID> R queryByThrough(String keyPreFix, Class<R> type, ID id, Function<ID, R> dfFllback, Long Time, TimeUnit timeUnit) {
        //缓存key
        String key = keyPreFix;
        //从redis查询
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        //存在则返回
        if (!StringUtils.isEmpty(json)) {
            return JSONUtil.toBean(json, type);
        }

        //不存在则从数据库中查询
        R r = dfFllback.apply(id);
        //判断数据库中是否有数据
        if (r == null) {
            //在redis中添加一个空,并设置过期时间
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, timeUnit);
            return null;
        }
        //数据库存在,则写入redis并返回
        this.set(key, r, Time, timeUnit);
        return r;
    }

}
